package com.example.qihuibao.widget.view

import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.widget.FrameLayout
import android.widget.ImageView
import android.widget.RadioButton
import android.widget.Switch
import android.widget.TextView
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.example.qihuibao.R
import com.example.qihuibao.constant.Config
import com.example.qihuibao.constant.Global
import com.example.qihuibao.module.main.MainActivity
import com.example.qihuibao.utils.ConnectUtil
import com.example.qihuibao.utils.IpUtil
import com.example.qihuibao.utils.extension.toast
import com.example.qihuibao.widget.dialog.YesOrNoDialog
import com.koushikdutta.async.http.WebSocket
import java.util.concurrent.ConcurrentHashMap

/**
 *     author : cwwei
 *     e-mail : 494545699@qq.com
 *     date   : 2022/08/13
 *     desc   :B屏：面向员工
 */
class BScreenLayout(ctx:Context) : FrameLayout(ctx) {
    private var activity:MainActivity? = null
    private lateinit var root:View
    private lateinit var tvName:TextView
    private lateinit var tvCount:TextView
    private lateinit var ivNetworkConnect:ImageView
    private lateinit var ivStationConnect:ImageView
//    private lateinit var rvConnectList:CommonRecyclerView
    private lateinit var tvWorkMode:TextView
    private lateinit var switchServer:Switch
    private lateinit var btnHome:RadioButton
    private lateinit var btnSetting:RadioButton
    private lateinit var flContent:FrameLayout
    private var homeLayout:HomeLayout? = null
    private var settingLayout:SettingLayout? = null
    private var alarmDialog:YesOrNoDialog? = null
    private var alarmDialogCloseCount = 0
    private var offlineFromStation = false

//    private val devices = mutableListOf<WebSocket>()

    init {
        if (ctx is MainActivity) {
            activity = ctx
        }
        root = LayoutInflater.from(ctx).inflate(R.layout.layout_bscreen, this, true)
        initView()
    }

    private fun initView() {
        tvName = root.findViewById(R.id.tv_name)
        tvCount = root.findViewById(R.id.tv_count)
        ivNetworkConnect = root.findViewById(R.id.iv_network_connect)
        ivStationConnect = root.findViewById(R.id.iv_station_connect)
        tvWorkMode = root.findViewById(R.id.tv_work_mode)
        switchServer = root.findViewById(R.id.switch_server)
//        rvConnectList = root.findViewById(R.id.rv_connect_list)
        btnHome = root.findViewById(R.id.rbtn_home)
        btnSetting = root.findViewById(R.id.rbtn_setting)
        flContent = root.findViewById(R.id.fl_content)
//        setName()
        tvName.setOnClickListener {
            ConnectUtil.groupSend()
        }
        switchServer.isChecked = Config.isStation
        switchServer.setOnCheckedChangeListener { buttonView, isChecked ->
            Config.isStation = isChecked
//            setName()
            activity?.configServerStation(isChecked)
        }
//        rvConnectList.init(
//            R.layout.item_connect_icon,
//            LinearLayoutManager(context, RecyclerView.HORIZONTAL, false),
//            devices,
//            {parent, pos ->
////                (parent as ImageView).setImageResource(R.drawable.ic_device)
//            }
//        )
//        btnSendToServer.setOnClickListener {
//            sendData(etData.text.toString())
//        }
        btnHome.setOnClickListener {
            showHomeLayout()
        }
        btnSetting.setOnClickListener {
            showSettingLayout()
        }
        //
        btnHome.performClick()
    }
    
    
    //
    private fun showHomeLayout() {
        if (flContent.childCount == 1 && flContent.getChildAt(0) == homeLayout) {
            return
        }
        flContent.removeAllViews()
        if (homeLayout == null) {
            homeLayout = HomeLayout(context)
        }
        flContent.addView(homeLayout!!)
        Global.pageId = 1
    }

    private fun showSettingLayout() {
        if (flContent.childCount == 1 && flContent.getChildAt(0) == settingLayout) {
            return
        }
        flContent.removeAllViews()
        if (settingLayout == null) {
            settingLayout = SettingLayout(context)
        }
        flContent.addView(settingLayout!!)
        Global.pageId = 2
    }

//    fun setServerChecked(checked:Boolean) {
//        switchServer.isChecked = checked
//        setName()
//    }

//    fun showConnectAsServer(connects: HashMap<String, WebSocket>) {
//        devices.clear()
//        for (bean in connects) {
//            devices.add(bean.value)
//        }
//        rvConnectList.adapter?.notifyDataSetChanged()
//        ivConnect.visibility = View.GONE
//        setName()
//    }

    fun showConnect(connectICBC :Boolean, connectStation :Boolean, connectList: ConcurrentHashMap<String, WebSocket>?) {
        ivNetworkConnect.setImageResource(if (connectICBC && Global.networkOk) R.drawable.ic_connect else R.drawable.ic_disconnect)
        tvName.text = "${if (Config.isStation) "服务站" else "终端"} ${IpUtil.getHostIP()}"
        tvCount.visibility = if (Config.isStation) View.VISIBLE else View.GONE
        ivStationConnect.visibility = if (Config.isStation) View.GONE else View.VISIBLE
        switchServer.isChecked = Config.isStation
        if (Config.isStation) {
            tvCount.text = "终端在线：${connectList?.size?:0}"
//            rvConnectList.visibility = View.VISIBLE
//            if (connectList != null) {
//                if (connectList.size != devices.size) {
//                    devices.clear()
//                    for (item in connectList) {
//                        devices.add(item.value)
//                    }
//                    rvConnectList.adapter?.notifyDataSetChanged()
//                }
//            }
        }else {
            ivStationConnect.setImageResource(if (connectStation) R.drawable.ic_station_connect else R.drawable.ic_station_disconnect)
//            rvConnectList.visibility = View.INVISIBLE
        }
        //offline alarm
        if (Config.isStation) {
            if (!connectICBC || !Global.networkOk) {
                showConnectAlarmDialog()
            }else {
                hideConnectAlarmDialog()
            }
        }else {
            if (offlineFromStation) {//服务站要求client无条件进入离线模式
                if (Global.workMode == 0) {
                    Global.workMode = 1
                    tvWorkMode.text = "[服务站离线模式]"
                    context.toast("进入服务站离线模式")
                }
                return
            }
            if ((!connectICBC || !Global.networkOk) && !connectStation) {
                showConnectAlarmDialog()
            }else {
                hideConnectAlarmDialog()
            }
        }
    }

    private fun showConnectAlarmDialog() {
        //发出警告，指引切入局域网离线工作模式
        if (alarmDialog == null) {
            alarmDialog = YesOrNoDialog("警告", "设备已离线，继续使用请点击[确定]进入离线模式。\n\n注意：进入离线模式可能会出现取餐重复及消费记录重复.") {
                if (it) {
                    setWorkMode(false)
                }else {
                    alarmDialogCloseCount = Global._30S
                }
            }
            alarmDialog?.show(activity!!.supportFragmentManager, "alarm")
        }else {
            if (alarmDialogCloseCount > 0) {
                if (--alarmDialogCloseCount == 0) {
                    alarmDialog = null
                }
            }
        }
    }

    private fun hideConnectAlarmDialog() {
        alarmDialog?.dismiss()
        alarmDialog = null
        setWorkMode(true)
    }

    private fun setWorkMode(normal:Boolean) {
        if (normal) {
            if (Global.workMode != 0) {
                Global.workMode = 0
                tvWorkMode.text = "[正常模式]"
                context.toast("已退出离线模式")
                if (Config.isStation) {
                    activity?.sendDataToAllClients("station online")
                }
            }
        }else {
            if (Global.workMode == 0) {
                Global.workMode = 1
                tvWorkMode.text = "[离线模式]"
                context.toast("进入离线模式")
                if (Config.isStation) {
                    activity?.sendDataToAllClients("station offline")
                }
            }
        }
    }

    fun setOffline(off:Boolean) {
        offlineFromStation = off
    }

    fun getHomeLayout() : HomeLayout? {
        return homeLayout
    }

    fun showDevInit() {
        btnHome.performClick()
        homeLayout?.showDevInit()
    }

}